// @ 516
// _(:з」∠)_

define([ "layDate" ], function( laydate ) {
    'use strict';

    return {
        pointInfo: {},
        disDetilas: function( param ) {
            let disUrl = "",
                disasterDate = "",
                lineBox = document.querySelector(".timeLine"),
                disItem = document.querySelector(".disaster_box .ul_list > .li_item.select");

            disasterDate = disItem.getAttribute("endtime");
            if ( lineBox ) disasterDate = lineBox.querySelector(".line_item.select").getAttribute("time");

            if ( param.disModel == "T1" ) {
                disUrl = "/disaster/getDisasterEventDetail?"
                +"disasterArea="+ param.disArea +"&cropName=Winter wheat"
                +"&disasterType="+ param.disType +"&modelValue="+ param.disModel
                +"&disasterDate="+ disasterDate;
            } else {
                disUrl = "/disaster/getDisasterEventDetailByEventId?"
                +"disasterArea="+ param.disArea +"&cropName=Winter wheat"
                +"&eventId="+ param.disEvent +"&modelValue="+ param.disModel +"&disasterType="+ param.disType;
            }

            RST.basic( NetWorkPath + disUrl, "", function( reuslt ) {
                if ( reuslt.data ) {
                    let thisView = ``, total = ``,
                        data = reuslt.data;

                    if ( param.disModel == "T1" || param.disModel == "T2" ) total = `<li> <h>受灾面积:</h> <span>${ data.totalArea * 100  } hm² (公顷)</span> </li>`;
                    if ( param.disModel == "T3" ) total = `<li> <h>受灾损失率:</h> <span>${ data.totalLoss  } % (损失率)</span> </li>`;

                    if ( param.type == "point" ) {
                        thisView = `<div class="dis_info">
                                        <div class="rightInfo_head">受灾详情</div>
                                        <ul>
                                            <li> <h>受灾区域:</h> <span>${ data.areaName }</span> </li>
                                            <li> <h>受灾作物:</h> <span>${ data.cropNameCN }</span> </li>
                                            <li> <h>受灾类型:</h> <span>${ data.disasterName }</span> </li>
                                            ${ total }
                                            <li> <h>受灾时序:</h> <span>${ data.disasterDate }</span> </li>
                                        </ul>
                                    </div>`;
                    } else {
                        thisView = `<div class="dis_info">
                                        <div class="rightInfo_head">受灾详情</div>
                                        <ul>
                                            <li> <h>受灾区域:</h> <span>${ data.areaName }</span> </li>
                                            <li> <h>受灾作物:</h> <span>${ data.cropNameCN }</span> </li>
                                            <li> <h>受灾类型:</h> <span>${ data.disasterName }</span> </li>
                                            ${ total }
                                            <li> <h>受灾时序:</h> <span>${ data.disasterDate }</span> </li>
                                        </ul>
                                    </div>
                                    <div class="disAdressInfo">
                                        <div class="rightInfo_head">受灾区县</div>
                                        <div class="dis_table">
                                            <div id="disAdress_table"></div>
                                        </div>
                                    </div>`;
                    }
        
                    param.insetElmt.insertAdjacentHTML("beforeEnd", thisView);

                    // element ->
                    let disTable = param.insetElmt.querySelector("#disAdress_table");

                    if ( disTable && param.type == "area" ) {
                        setTimeout(function() {
                            let tablePage = false,
                                elmtWidth = disTable.parentNode.clientWidth,
                                elmtHeight = 10 * 24 + 30;
                            
                            if ( data.detail.length > 10 ) tablePage = true;

                            // 处理数据组合
                            let newData = [],
                                singleData = objToHeavy( data.detail, "fullAdminName" );

                            for ( let x = 0; x < singleData.length; x++ ) {
                                for ( let y = 0; y < data.detail.length; y++ ) {
                                    if ( data.detail[y].fullAdminName == singleData[x].fullAdminName ) {
                                        newData.push( data.detail[y] );
                                    }
                                }
                            }

                            if ( param.disModel == "T3" ) {
                                Tablex.singleTable({
                                    elmt: disTable,
                                    option: {
                                        data: newData,
                                        width: elmtWidth, height: elmtHeight,
                                        columns: [
                                            { data: 'fullAdminName', type: 'text', width: ( elmtWidth * 0.6 ), className: 'htMiddle trOne', editor: false },
                                            { data: 'cropNameCN', type: 'text', width: ( elmtWidth * 0.2 ), className: 'htCenter htMiddle', editor: false },
                                            { data: 'disasterLoss', type: 'numeric', width: ( elmtWidth * 0.2 ), className: 'htCenter htMiddle', editor: false,
                                                numericFormat: { pattern: '0' }
                                            }
                                        ],
                                        stretchH: 'all', fillHandle: false,
                                        rowHeaders: false, autoWrapRow: true,
                                        colHeaders: [ '区县', '作物', '损失率(%)' ]
                                    },
                                    tablePage: tablePage
                                });
                            } else {
                                // 处理数据单位变化
                                for ( let x = 0; x < newData.length; x++ ) {
                                    newData[x].disasterArea = newData[x].disasterArea * 100;
                                }
                                
                                Tablex.singleTable({
                                    elmt: disTable,
                                    option: {
                                        data: newData,
                                        width: elmtWidth, height: elmtHeight,
                                        columns: [
                                            { data: 'fullAdminName', type: 'text', width: ( elmtWidth * 0.48 ), className: 'htMiddle trOne', editor: false },
                                            { data: 'cropNameCN', type: 'text', width: ( elmtWidth * 0.18 ), className: 'htCenter htMiddle', editor: false },
                                            { data: 'disasterLevelName', type: 'text', width: ( elmtWidth * 0.14 ), className: 'htCenter htMiddle', editor: false },
                                            { data: 'disasterArea', type: 'numeric', width: ( elmtWidth * 0.2 ), className: 'htCenter htMiddle', editor: false,
                                                numericFormat: { pattern: '0' }
                                            }
                                        ],
                                        // mergeCells: [
                                        //     { row:0, col:0, rowspan: 3, colspan:1 }
                                        // ],
                                        stretchH: 'all', fillHandle: false,
                                        rowHeaders: false, autoWrapRow: true,
                                        colHeaders: [ '区县', '作物', '程度', '面积(hm²)' ]
                                    },
                                    tablePage: tablePage
                                });
                            }
                        }, 100);
                    }
                } else {
                    param.insetElmt.insertAdjacentHTML("beforeEnd", `<p class="noData">未获取到当前相关数据信息</p>`);
                }
            });
        },
        areaStation: function( param ) {
            let _this = this,
                thisView = `<div class="stationDetails">
                                        <div class="rightInfo_head">小气候站</div>
                                        <div class="moreOpt">
                                            <button type="button" name="distribution">分布图</button>
                                        </div>
                                        <div class="dis_table">
                                            <div id="station_table"></div>
                                        </div>
                                    </div>`;

            param.insetElmt.insertAdjacentHTML("beforeEnd", thisView);
            let stationTable = param.insetElmt.querySelector("#station_table");

            RST.basic( NetWorkPath + "/device/getWeatherDeviceByAreaName?areaName=HHH", "", function( result ) {
                if ( result.data ) {
                    let newData = [];

                    for ( let x = 0; x < result.data.length; x++ ) {
                        let data = result.data[x],
                            dataDetails = data.detail;

                        let latLng = MC.mapEvent.AlbersTolngLat(
                                MC.customCRS,
                                {
                                    lng: dataDetails[0].deviceLon,
                                    lat: dataDetails[0].deviceLat
                                }
                            );

                        newData.push({
                            check: false,
                            name: data.deviceName,
                            cropName: dataDetails[0].cropName,
                            albersLat: latLng.albersLat,
                            albersLng: latLng.albersLng,
                            lat: latLng.lat,
                            lng: latLng.lng
                        });
                    }

                    let tablePage = false,
                        elmtWidth = stationTable.parentNode.clientWidth,
                        elmtHeight = 10 * 24 + 30;
                    
                    if ( result.data.length > 10 ) {
                        tablePage = true;
                    } else {
                        elmtHeight = result.data.length * 24 + 20;
                    }

                    Tablex.singleTable({
                        elmt: stationTable,
                        option: {
                            data: newData,
                            width: elmtWidth, height: elmtHeight,
                            columns: [
                                { data: 'check', type: 'checkbox',
                                    label: {
                                        position: 'after',
                                        property: 'name'
                                    }, width: ( elmtWidth * 0.4 ), className: 'htMiddle clickEvent', editor: false },
                                { data: 'cropName', type: 'text', width: ( elmtWidth * 0.6 ), className: 'htMiddle', editor: false },
                            ],
                            stretchH: 'all', fillHandle: false,
                            rowHeaders: false, autoWrapRow: true,
                            colHeaders: [ '站名', '作物' ]
                        },
                        tablePage: tablePage
                    });

                    let clickEvent = param.insetElmt.querySelectorAll("td.clickEvent"),
                        distribution = param.insetElmt.querySelector("button[name='distribution']");

                    for ( let x = 0; x < clickEvent.length; x++ ) {
                        clickEvent[x].querySelector("input").setAttribute( "type", "radio" );
                        clickEvent[x].querySelector("input").setAttribute( "name", "stationInfo" );
                    }

                    for ( let x = 0; x < clickEvent.length; x++ ) {
                        clickEvent[x].addEventListener( 'click', function(e) {
                            if ( e.target.nodeName == "INPUT" || e.target.parentNode == "TD" ) {
                                let deInfo = param.insetElmt.querySelector(".stationDetailsInfo");
                                if ( deInfo ) deInfo.remove();

                                let infoHtml = `<div class="stationDetailsInfo">
                                                            <div class="rightInfo_head">${ newData[x].name } - 详细信息</div>
                                                            <div class="tempChangeTrend">
                                                            <div class="dis_chart" id="station_temp_chart"></div>
                                                        </div>`;
                                param.insetElmt.insertAdjacentHTML("beforeEnd", infoHtml);
                                deInfo = param.insetElmt.querySelector(".stationDetailsInfo");

                                _this.areaStationDetails( deInfo, newData[x] );
                                weatherStation.init({});
                            }
                            e.stopPropagation();
                        }, false);
                    }

                    distribution.addEventListener( 'click', function( e ) {
                        MC.mapEvent.drawFarmlandStations( newData, function( result ) {
                            let index = result.target.options.index,
                                table = document.querySelector("#station_table");
                            table.querySelectorAll(".clickEvent")[index].querySelector("input").click();
                        });
                    }, false);
                } else {
                    param.insetElmt.insertAdjacentHTML("beforeEnd", `<p class="noData">未获取到当前相关数据信息</p>`);
                }
            });
        },
        areaStationDetails: function( elmt, param ) {
            let _this = this,
                thisTime = formatTime( "", "day" ),
                observeTime = formatTime( new Date( thisTime ), "day", -(4 * 24 * 60 * 60 * 1000) ),
                forecastTime = formatTime( new Date( thisTime ), "day", (2 * 24 * 60 * 60 * 1000) );

            // 基础数据chart
            RST.basic( NetWorkPath + "/grid/getGridData?group=weather"
                +"&type=observe&elements=TEM_Min,TEM_Max,TEM_Avg&fileType=tif"
                +"&startDate="+ observeTime +"&endDate="+ thisTime
                +"&lon="+ param.albersLng +"&lat="+ param.albersLat, "",
            function( reuslt ) {
                let tmpObserve = [];

                if ( reuslt.data ) {
                    tmpObserve = reuslt.data.observe;
                } else {
                    console.log( "未获取到相应温度实况数据" );
                }

                RST.basic( NetWorkPath + "/grid/getGridData?group=weather"
                    +"&type=forecast&elements=TEM_Min,TEM_Max&fileType=tif"
                    +"&startDate="+ thisTime +"&endDate="+ forecastTime
                    +"&lon="+ param.albersLng +"&lat="+ param.albersLat, "",
                function( reusltx ) {
                    let dataArry = [ tmpObserve, [] ],
                        temp_chart = elmt.querySelector("#station_temp_chart");
                        
                    if ( reusltx.data ) {
                        dataArry = [ tmpObserve, reusltx.data.forecast ];
                    } else {
                        console.log( "未获取到相应温度预报数据" );
                    }
                    
                    if ( temp_chart && dataArry[0].length > 0 && dataArry[1].length > 0 ) {
                        Chartx.temp_echarts({
                            elmt: temp_chart,
                            data: dataArry
                        });
                    } else {
                        
                    }
                });
            });

            // 详情信息弹窗
            
        },
        disBackInfo: function( param ) {
            let _this = this,
                thisView = ``;

            thisView += `<div class="tempChangeTrend">
                            <div class="rightInfo_head">气温变化趋势</div>
                            <div class="temp_box">
                                <ul class="temp_box_head">
                                    <li type="TEM_Min">最低气温</li>
                                    <li type="TEM_Max">最高气温</li>
                                    <li type="TEM_Avg">平均气温</li>
                                </ul>
                                <div class="dis_chart" id="temp_chart"></div>
                                <ul class="temp_box_bottom">
                                    <li> <span>历史范围</span> <input type="text" id="history" name="history" readonly="readonly" /> </li>
                                    <li> <span>常年范围</span> <input type="text" id="perennial" name="perennial" readonly="readonly" /> </li>
                                </ul>
                            </div>
                        </div>
                        <div class="precChangeTrend">
                            <div class="rightInfo_head">降水量变化趋势</div>
                            <div class="dis_chart" id="prec_chart"></div>
                        </div>`;

            if ( param.disModel == "T2" && param.type == "point" ) {
                thisView += `<div class="ndviChangeTrend">
                                <div class="rightInfo_head">NDVI(植被)变化趋势</div>
                                <div class="moreOpt">
                                    <button type="button" name="distribution">分布图</button>
                                </div>
                                <div class="dis_chart" id="ndvi_chart"></div>
                            </div>`;
            }

            param.insetElmt.insertAdjacentHTML("beforeEnd", thisView);

            let disBox = document.querySelector(".disaster_box"),
                disTime = disBox.querySelector(".ul_list > .li_item.select"),
                disStartTime = formatTime( disTime.getAttribute("startime"), "day", -( 3 * 24 * 60 * 60 * 1000 ) ),
                disEndTime = disTime.getAttribute("endtime");
            
            // 分布图
            let distribution = param.insetElmt.querySelectorAll("button[name='distribution']");
            for ( let x = 0; x < distribution.length; x++ ) {
                distribution[x].addEventListener( 'click', function( e ) {
                    let parentClass = distribution[x].parentNode.classList[0];
                    switch( parentClass ) {
                        case "tempChangeTrend":
                            break;
                        case "precChangeTrend":
                            break;
                        case "ndviChangeTrend":
                            MC.mapEvent.drawImageLayer( "/simulation/HHH/T2/2018-04-06/2018-04-06.png" );
                            break;
                    }
                }, false);
            }

            
            let temp_chart = document.querySelector("#temp_chart"),
                prec_chart = document.querySelector("#prec_chart"),
                tempList = document.querySelector(".tempChangeTrend .temp_box_head");
            
            let _stime = new Date( disStartTime ),
                _etime = new Date( disEndTime ),
                _year = _stime.getFullYear(),
                _month = _stime.getMonth() + 1,
                _sday = _stime.getDate(),
                _eday = _etime.getDate();
            
            ( _month < 10 ) ? _month = "0"+_month : _month;
            ( _sday < 10 ) ? _sday = "0"+_sday : _sday;
            ( _eday < 10 ) ? _eday = "0"+_eday : _eday;

            // 初始化时间选择
            laydate.render({
                elem: '#history'
                ,type: 'year'
                ,range: true
                ,value: '2013 - 2018'
                ,trigger: 'click'
                ,done: function( value, date ) {
                    _this.initChartShow({
                        chart: "history",
                        type: "temp",
                        elmt: tempList.querySelector("li.select").getAttribute("type"),
                        startTime: disStartTime,
                        endTime: disEndTime,
                        startDate: (_year-3)+"-"+_month+"-"+_sday,
                        endDate: (_year-3)+"-"+_month+"-"+_eday,
                        startYear: value.split(" - ")[0],
                        endYear: value.split(" - ")[1],
                        month: _month,
                        sday: _sday,
                        eday: _eday
                    });
                }
            });

            laydate.render({
                elem: '#perennial'
                ,type: 'year'
                ,range: true
                ,value: '1981 - 2010'
                ,trigger: 'click'
                ,done: function( value, date ) {
                    console.log( value, date );
                }
            });

            // 切换温度
            tempList.addEventListener( "click", function(e) {
                if ( e.target.nodeName == "LI" ) {
                    e.target.removeAllClass("select");
                    e.target.addClass("select");

                    let historyVal = document.querySelector("input#history").value.split(" - ");

                    _this.compareStation( {
                        lng: param.latlng[1], lat: param.latlng[0]
                    }, function() {
                        _this.initChartShow({
                            chart: "all",
                            type: "temp",
                            elmt: e.target.getAttribute("type"),
                            startTime: disStartTime,
                            endTime: disEndTime,
                            startDate: (_year-3)+"-"+_month+"-"+_sday,
                            endDate: (_year-3)+"-"+_month+"-"+_eday,
                            startYear: _year-5,
                            endYear: _year,
                            month: _month,
                            sday: _sday,
                            eday: _eday
                        });
                    });
                }

                return false;
            }, false);

            tempList.querySelectorAll("li")[0].click();

            setTimeout(function() {
                _this.initChartShow({
                    chart: "all",
                    type: "prec",
                    elmt: "PRE",
                    startTime: disStartTime,
                    endTime: disEndTime,
                    startDate: (_year-3)+"-"+_month+"-"+_sday,
                    endDate: (_year-3)+"-"+_month+"-"+_eday,
                    startYear: _year-5,
                    endYear: _year,
                    month: _month,
                    sday: _sday,
                    eday: _eday
                });
            }, 500);
        },
        initChartShow: function( param ) {
            let _this = this,
                timeRange = [];

            if ( param.chart == "all" || param.chart == "observe" ) {
                if ( param.type != "prec" ) {
                    RST.basic(
                        _this.getChartDataUrl({
                            type: "observe",
                            elmt: param.elmt,
                            startTime: param.startTime,
                            endTime: param.endTime
                        }), "",
                    function( reuslt ) {
                        if ( reuslt.data ) {
                            let sort_ = reuslt.data.observe.sort( objTimeCompare( "dataDate" ) ),
                                category = [], seriesData = [], option = null;
        
                            for ( let x = 0; x < sort_.length; x++ ) {
                                category.push( sort_[x].dataDate );
                                let value = Math.round( sort_[x][ param.elmt.toLowerCase() ] * 10 ) / 10;
                                if ( param.type == "prec" ) {
                                    ( value < 0 ) ? value = 0 : value;
                                }
                                seriesData.push( value );
                            }
        
                            switch( param.type ) {
                                case "temp":
                                    Chartx.temp_echarts({ elmt: temp_chart });
        
                                    option = Chartx.chartArry.temp_chart.getOption();
                                    option.xAxis[0].data = category;
                                    option.series[1].data = seriesData;
        
                                    Chartx.chartArry.temp_chart.setOption( option );

                                    Chartx.prec_echarts({ elmt: prec_chart });
                                    option = Chartx.chartArry.prec_chart.getOption();
                                    option.xAxis[0].data = category;
                                    option.series[1].data = [ 9.2, 3.7, 0, 0, 0, 0, 0, 0, 0 ];
                                    Chartx.chartArry.prec_chart.setOption( option );

                                    option = null;
                                break;
                                case "prec":
                                    Chartx.prec_echarts({ elmt: prec_chart });
        
                                    option = Chartx.chartArry.prec_chart.getOption();
                                    option.xAxis[0].data = category;
                                    option.series[1].data = seriesData;
        
                                    Chartx.chartArry.prec_chart.setOption( option );
                                    option = null;
                                break;
                            }
                        } else {
                            Popup.tipPopup({ type: "toast", content: "实况值获取失败" });
                        }
                    });
                }
            }

            if ( param.chart == "all" || param.chart == "history" ) {
                let dayLent = Number( param.eday ) - Number( param.sday );
                for ( let x = 0 ; x < dayLent+1; x++ ) {
                    RST.basic(
                        _this.getChartDataUrl({
                            type: "history",
                            elmt: param.elmt,
                            startYear: param.startYear,
                            endYear: param.endYear,
                            month: Number( param.month ),
                            day: Number( param.sday ) + x
                        }), "",
                    function( reuslt ) {
                        if ( reuslt.data ) {
                            let option = null,
                                value = Math.round( reuslt.data.statisticValue * 10 ) / 10;
                            if ( param.type == "prec" ) {
                                ( value < 0 ) ? value = 0 : value;
                            }
        
                            switch( param.type ) {
                                case "temp":
                                    option = Chartx.chartArry.temp_chart.getOption();

                                    if ( option.series[0].data.length >= dayLent+1 ) {
                                        option.series[0].data = [];
                                        Chartx.chartArry.temp_chart.setOption( option );
                                    }

                                    option.series[0].data.push( value );
                                
                                    Chartx.chartArry.temp_chart.setOption( option );
                                    option = null;
                                break;
                                case "prec":
                                    option = Chartx.chartArry.prec_chart.getOption();

                                    if ( option.series[0].data.length >= dayLent+1 ) {
                                        option.series[0].data = [];
                                        Chartx.chartArry.prec_chart.setOption( option );
                                    }

                                    option.series[0].data.push( value );
        
                                    Chartx.chartArry.prec_chart.setOption( option );
                                    option = null;
                                break;
                            }
                        } else {
                            Popup.tipPopup({ type: "toast", content: "历史值获取失败" });
                        }
                    });
                }
            }

            if ( param.chart == "all" || param.chart == "perennial" ) {
                RST.basic(
                    _this.getChartDataUrl({
                        type: "perennial",
                        elmt: param.elmt,
                        startDate: param.startDate,
                        endDate: param.endDate
                    }), "",
                function( reuslt ) {
                    if ( reuslt.data ) {
                        let sort_ = reuslt.data.sort( objTimeCompare( "statisticDate" ) ),
                            seriesData = [], option = null;
    
                        for ( let x = 0; x < sort_.length; x++ ) {
                            let value = Math.round( sort_[x].statisticValue * 10 ) / 10;
                            if ( param.type == "prec" ) {
                                ( value < 0 ) ? value = 0 : value;
                            }
                            seriesData.push( value );
                        }
    
                        switch( param.type ) {
                            case "temp":
                                option = Chartx.chartArry.temp_chart.getOption();
                                option.series[2].data = seriesData;
    
                                Chartx.chartArry.temp_chart.setOption( option );
                                option = null;
                            break;
                            case "prec":
                                option = Chartx.chartArry.prec_chart.getOption();
                                option.series[2].data = seriesData;
    
                                Chartx.chartArry.prec_chart.setOption( option );
                                option = null;
                            break;
                        }
                    } else {
                        Popup.tipPopup({ type: "toast", content: "常年值获取失败" });
                    }
                });
            }
        },
        compareStation: function( param, execute ) {
            let _this = this;

            // 转换投影经纬度
            let _latLng_ = proj4( MC.China_Albers ).inverse([ param.lng, param.lat ]);

            _this.pointInfo["lng"] = _latLng_[0];
            _this.pointInfo["lat"] = _latLng_[1];
            _this.pointInfo["albersLng"] = param.lng;
            _this.pointInfo["albersLat"] = param.lat;

            // 获取地理位置信息
            RST.lngLatTurnAddress(
                { lat: _latLng_[1], lng: _latLng_[0] },
            function( result ) {
                let address = result.regeocode.addressComponent,
                    areaName = address.province+address.city+address.district;
                    
                _this.pointInfo["areaName"] = areaName;

                ( execute && typeof( execute ) === "function" ) && execute();
            });
        },
        getChartDataUrl: function( param ) {
            let _this = this,
                thisUrl = NetWorkPath,
                urlCont = ``;

            switch( param.type ) {
                case "observe":
                    urlCont += `/grid/getGridData?group=weather`
                                + `&type=observe&elements=${ param.elmt }&fileType=tif`
                                + `&startDate=${ param.startTime }&endDate=${ param.endTime }`
                                + `&lon=${ _this.pointInfo.albersLng }&lat=${ _this.pointInfo.albersLat }`;
                break;
                case "history":
                    urlCont += `/grid/statisticGridHistoryData?`
                            + `lon=${ _this.pointInfo.lng }&lat=${ _this.pointInfo.lat }&statisticElement=avg(${ param.elmt.toLowerCase() })`
                            + `&startYear=${ param.startYear }&endYear=${ param.endYear }&month=${ param.month }&day=${ param.day }`;
                break;
                case "perennial":
                    urlCont += `/grid/statisticGridYearlyData?`
                            + `lon=${ _this.pointInfo.lng }&lat=${ _this.pointInfo.lat }&statisticElement=${ param.elmt.toLowerCase() }`
                            + `&startDate=${ param.startDate }&endDate=${ param.endDate }`;
                break;
            }

            return thisUrl + urlCont;
        },
        disSituation: function( param ) {
            var codeArray = [],
                nameArray = [];
            if(param.disArea == "HHH"){ //黄淮 HHH
                codeArray = [11, 12, 13, 32, 34, 37, 41];
                nameArray = ["北京", "天津", "河北", "江苏", "安徽", "山东", "河北"];
            } else if(param.disArea == "NEA"){ //东北 NEA
                codeArray = [15, 21, 22, 23];
                nameArray = ["蒙古", "辽宁", "吉林", "黑龙江"];
            } else if(param.disArea == "MLY"){ //长江中下游 MLY
                codeArray = [31, 32, 33, 34, 36, 42, 43, 51];
                nameArray = ["上海", "江苏", "浙江", "安徽", "江西", "湖北", "湖南","四川"];
            }
            console.log(codeArray.join(','));
            // RST.basic( Path + "/simulation/disastersDetilas.json", "", function( reuslt ) {
            RST.basic( "http://118.25.235.213:8020/ChinaAPP/cloud/disaster/getPageDisasterList?pageNum=1&pageSise=12&type=1&areaCode="+ codeArray.join(',') +"", "", function( reuslt ) {
                let data = reuslt.data;//[ param.className ];

                // 灾害上报
                let disUploadInfo = ``;
                if(data == null || data.length <= 0){
                    disUploadInfo = `<li class="list_li" style="border: none; text-align: center; line-height: 60px;">暂无数据<li>`;
                    $(".disUploadInfo_ul").html(disUploadInfo);                   
                }else{
		            let datelength = data.length;
		            if(datelength >= 3){
			            datelength = 3
		            }	
                    for ( let x = 0; x < datelength; x++ ) {
                        var url = "";
                        if( data[x].disaImgs == null ){
                            url = "../image/image/noagrimage.png";
                        }else {
                            var imgArray = data[x].disaImgs.split(","); 
                                url = "http://118.25.235.213:8020/ChinaAPP/"+ imgArray[0];
                        }
                        var type = "";
                        if( data[x].leve1Name == null ){
                        }else {
                            type += data[x].leve1Name;
                        }
                        if( data[x].descriptTypeName == null ){
                        }else {
                            type += ","+data[x].descriptTypeName;
                        }
                        disUploadInfo += `<li class="list_li">
                                            <div class="img">
                                                <img src="${ url }" onclick="showimgdiv('${ url }')"/>
                                            </div>
                                            <div class="info">
                                                <h title="${ data[x].userShowName }">用户名: ${ data[x].userShowName }</h>
                                                <div class="typediv">`
                                                for(let v=0;v<type.split(",").length;v++){
                                                    if(v==0){
                                                        disUploadInfo += `<div class="borderdiv">${ type.split(",")[v] }</div>`;
                                                    }else{
                                                        disUploadInfo += `<div class="borderdiv" style="margin-left: 5px;">${ type.split(",")[1] }</div>`;
                                                    }
                                                }                                                     
                              disUploadInfo += `</div>
                                                <div class="disUploadInfo_des" title="${ data[x].descript }">${ data[x].descript }</div>
                                                <span style="width: 100%;">发布时间: ${ data[x].createtime.substring(0, 10) }</span>
                                            </div>
                                        </li>`;
                                        // <span style="width: 100%;">发布时间: ${ data[x].createtime.substring(0, 10) }</span>                                       
                    }
                }    

                // 网络舆情
                // let networkInfo = ``;
                // for ( let x = 0; x < data.networkInfo.length; x++ ) {
                //     networkInfo += `<li class="list_li">
                //                         <div class="img">
                //                             <img src="${ data.networkInfo[x].image }" />
                //                         </div>
                //                         <div class="info">
                //                             <h>${ data.networkInfo[x].text }</h>
                //                             <p>描述: ${ data.networkInfo[x].description }</p>
                //                             <span>来源: ${ data.networkInfo[x].source }</span>
                //                             <!-- <span>发布时间: ${ data.networkInfo[x].releaseTime }</span> -->
                //                         </div>
                //                     </li>`;
                // }
                let areacontentHtml = ``;
                for ( let c = 0; c < codeArray.length; c++ ) {
                    if(c == 0){ 
                       areacontentHtml += `<label><input style="margin-left: 0;" name="ck" value="${ codeArray[c] }" type="checkbox"  checked>${ nameArray[c] }</label>`;
                    }else{
                       areacontentHtml += `<label><input name="ck" value="${ codeArray[c] }" type="checkbox"  checked>${ nameArray[c] }</label>`;
                    }                   
                }

                let thisView = `<div class="situation_item">
                                    <div class="rightInfo_head">灾情上报</div>
                                    <div class="moreOpt">  
                                        <button type="button" name="distribution">分布图</button>
                                        <button id="agri_more" type="button" name="more">更多</button>
                                    </div> 
                                    <form id="choose_city" class="timediv">${ areacontentHtml }</form>                                  
                                    <div class="timediv">
                                        <input class="timer" id="start_t" placeholder="请选择起始时间">
                                        <input class="timer" id="end_t" placeholder="请选择截止时间">
                                        <div id="timesub">确定</div>
                                    </div>
                                    <ul class="disUploadInfo_ul"> ${ disUploadInfo } </ul>
                                </div>`;
                                // <div class="situation_item">
                                //     <div class="rightInfo_head">网络舆情</div>
                                //     <div class="moreOpt">
                                //         <button type="button" name="more">更多</button>
                                //     </div>
                                //     <ul class="networkInfo_ul">  </ul>
                                // </div>`; //${ networkInfo }                
                param.insetElmt.insertAdjacentHTML("beforeEnd", thisView);

                if(data.length <= 0){
                    $("#agri_more").attr("disabled","disabled");
                }else{
                    $("#agri_more").removeAttr("disabled");
                }

                //时间选择 初始值(当天日期)
                var nowdate = new Date(),
                    nowyears = nowdate.getFullYear(),
                    nowmonth = nowdate.getMonth()+1,
                    nowday = nowdate.getDate();
                    if(nowmonth < 10){
                        nowmonth = "0"+nowmonth;
                    }
                    if(nowday < 10){
                        nowday = "0"+nowday;
                    }
                    $("#start_t").val(nowyears+"-"+nowmonth+"-"+nowday);
                    $("#end_t").val(nowyears+"-"+nowmonth+"-"+nowday);

                var subpar = document.querySelector("#timesub");
                subpar.addEventListener("click", function(e) {
                    disSituationreload(param);
                }, false);

                let stationData = [{ "id": 0, "name": "- 站点 -", "value": -1 }];
                if ( param.insetElmt.querySelector("div[name='select'].fs_station") ) {
                    Elmt.select({ elmt: param.insetElmt.querySelector("div[name='select'].fs_station"), data: stationData });
                }

                //同时绑定多个
                lay('.timer').each(function(){
                    laydate.render({
                       elem: this
                    });
                });     

                // laydate.render({
                //     elem: '.timer'
                // });

                // 加载更多信息
                let moreBtn = param.insetElmt.querySelectorAll("button[name='more']");
                for ( let x = 0; x < moreBtn.length; x++ ) {
                    // moreBtn[x].disabled = "false";
                    moreBtn[x].removeEventListener("click", Popup.moreInfoPanel, false);
                    moreBtn[x].removeEventListener("click", Popup.moreInfoPanel, false);
                    moreBtn[x].addEventListener("click", function(e) {
                        Popup.moreInfoPanel("11", data);
                    }, false);
                }

                let newData = [],
                    distribution = param.insetElmt.querySelector("button[name='distribution']");

                for ( let x = 0; x < data.length; x++ ) {
                    let latLng = MC.mapEvent.AlbersTolngLat(
                            MC.customCRS,
                            {
                                lng: Number( data[x].disaLongitud ),
                                lat: Number( data[x].disaLatitude )
                            }
                        );

                    newData.push({
                        check: false,
                        name: data[x].descriptTypeName,
                        cropName: data[x].leve1Name,
                        albersLat: latLng.albersLat,
                        albersLng: latLng.albersLng,
                        lat: latLng.lat,
                        lng: latLng.lng
                    });
                }

                distribution.addEventListener( 'click', function( e ) {
                    MC.mapEvent.disSituation( newData, function( result ) {
                        console.log( "灾害点触发" );
                    });
                }, false);
            });
        },  
        disReduction: function( param ) {
            let thisView = `<div class="technology">
                                <div class="rightInfo_head">条件筛选</div>
                                <div class="technology_head">
                                    <div name="select" class="ty_dis">
                                        <h></h> <ul></ul>
                                    </div>
                                    <div name="select" class="ty_crop">
                                        <h></h> <ul></ul>
                                    </div>
                                    <div name="select" class="ty_type">
                                        <h></h> <ul></ul>
                                    </div>
                                    <button type="button" name="ty_search">检索</button>
                                </div>
                                <div class="technology_cont">
                                    <div class="rightInfo_head">技术应用方法</div>
                                    <ul class="technology_list"></ul>
                                </div>
                            </div>`;

            param.insetElmt.insertAdjacentHTML("beforeEnd", thisView);

            RST.basic( Path + "/data/basic/filiter.json", "", function( result ) {
                let disData = [{ "id": 0, "pId": 0, "name": "- 灾种 -", "value": -1, "pName": "" }].concat( result.data.disaster ),
                    cropData = [{ "id": 0, "pId": 0, "name": "- 作物 -", "value": -1, "pName": "" }].concat( result.data.crop ),
                    typeData = [{ "id": 0, "pId": 0, "name": "- 技术 -", "value": -1, "pName": "" }];
                
                Elmt.select({ elmt: param.insetElmt.querySelector("div[name='select'].ty_dis"), data: disData });
                Elmt.select({ elmt: param.insetElmt.querySelector("div[name='select'].ty_crop"), data: cropData });
                Elmt.select({ elmt: param.insetElmt.querySelector("div[name='select'].ty_type"), data: typeData });
            });

            RST.basic( Path + "/simulation/disastersDetilas.json", "", function( reuslt ) {
                let data = reuslt.data[ param.className ],
                    thisElmt = param.insetElmt.querySelector(".technology_list"),
                    elmtView = ``;
                
                for ( let x = 0; x < data.length; x++ ) {
                    elmtView += `<li>
                                    <h>${ x+1 }. ${ data[x].text }</h>
                                    <p>${ data[x].description }</p>
                                </li>`;
                }

                thisElmt.insertAdjacentHTML("beforeEnd", elmtView);

            });
        },
        farmWork: function( param ) {
            let thisView = `<div class="growthPeriod">
                                <div class="rightInfo_head">作物生育期</div>
                                <div class="dis_table">
                                    <div id="growthPeriod_table"></div>
                                </div>
                            </div>
                            <div class="farmingActivit">
                                <div class="rightInfo_head">农事活动记录</div>
                                <div class="dis_table">
                                    <div id="farmingActivit_table"></div>
                                </div>
                            </div>`;

            param.insetElmt.insertAdjacentHTML("beforeEnd", thisView);

            RST.basic( Path + "/simulation/disastersDetilas.json", "", function( reuslt ) {
                let data = reuslt.data[ param.className ];

                // element ->
                let growthPeriod = param.insetElmt.querySelector("#growthPeriod_table"),
                    farmingActivit = param.insetElmt.querySelector("#farmingActivit_table");

                if ( growthPeriod ) {
                    setTimeout(function() {
                        let elmtWidth = growthPeriod.parentNode.clientWidth,
                            elmtHeight = data.growthPeriod.length * 24 + 29;

                        Tablex.singleTable({
                            elmt: growthPeriod,
                            option: {
                                data: data.growthPeriod,
                                width: elmtWidth, height: elmtHeight,
                                columns: [
                                    { data: 'variety', type: 'text', width: 128, className: 'htMiddle', editor: false },
                                    { data: 'acreage', type: 'numeric', className: 'htCenter htMiddle', editor: false,
                                        numericFormat: { pattern: '0.00' }
                                    },
                                    { data: 'growthPeriod_1', type: 'text', width: 80, className: 'htCenter htMiddle', editor: false },
                                    { data: 'growthPeriod_2', type: 'text', width: 66, className: 'htCenter htMiddle', editor: false },
                                    { data: 'growthPeriod_3', type: 'text', width: 66, className: 'htCenter htMiddle', editor: false },
                                    { data: 'growthPeriod_4', type: 'text', width: 66, className: 'htCenter htMiddle', editor: false },
                                    { data: 'growthPeriod_5', type: 'text', width: 66, className: 'htCenter htMiddle', editor: false },
                                    { data: 'growthPeriod_6', type: 'text', width: 66, className: 'htCenter htMiddle', editor: false },
                                    { data: 'growthPeriod_7', type: 'text', width: 66, className: 'htCenter htMiddle', editor: false },
                                    { data: 'growthPeriod_8', type: 'text', width: 66, className: 'htCenter htMiddle', editor: false },
                                    { data: 'growthPeriod_9', type: 'text', width: 66, className: 'htCenter htMiddle', editor: false }
                                ],
                                stretchH: 'all', fillHandle: false,
                                rowHeaders: false, autoWrapRow: true,
                                colHeaders: [ '品种', '面积(亩)', '播种', '出苗', '分蘖', '分蘖停止', '越冬', '返青', '拔节', '抽穗', '成熟' ]
                            }
                        });

                        // 比较生育期时间范围
                        let thisTime = new Date(),
                            thisYear = thisTime.getFullYear();

                        for ( let x = 0; x < data.growthPeriod.length; x++ ) {
                            let growths = [];
                            for ( let y in data.growthPeriod[x] ) {
                                if ( y.indexOf("growthPeriod") > -1 ) {
                                    growths.push( data.growthPeriod[x][y] );
                                }
                            }

                            for ( let y = 0; y < growths.length; y++ ) {
                                let thisGrowth = new Date( thisYear+"-"+growths[y] ),
                                    growthMonth = thisGrowth.getMonth() + 1,
                                    growthDay = thisGrowth.getDate(),
                                    growthXUN = "",
                                    currentMonth = thisTime.getMonth() + 1,
                                    currentDay = thisTime.getDate(),
                                    currentXUN = "";

                                switch( true ) {
                                    case growthDay > 0 && growthDay <= 10:
                                        growthXUN = growthMonth + "上旬";
                                        break;
                                    case growthDay > 10 && growthDay <= 20:
                                        growthXUN = growthMonth + "中旬";
                                        break;
                                    case growthDay > 20 && growthDay <= 31:
                                        growthXUN = growthMonth + "下旬";
                                        break;
                                }

                                switch( true ) {
                                    case currentDay > 0 && currentDay <= 10:
                                        currentXUN = currentMonth + "上旬";
                                        break;
                                    case currentDay > 10 && currentDay <= 20:
                                        currentXUN = currentMonth + "中旬";
                                        break;
                                    case currentDay > 20 && currentDay <= 31:
                                        currentXUN = currentMonth + "下旬";
                                        break;
                                }

                                if ( growthXUN == currentXUN ) {
                                    let growthTD = growthPeriod.querySelectorAll("tr")[x+1].querySelectorAll("td")[y+2];
                                    growthTD.addClass("growth");
                                }
                            }
                        }
                    }, 100);
                }

                if ( farmingActivit ) {
                    setTimeout(function() {
                        let elmtWidth = farmingActivit.parentNode.clientWidth,
                            elmtHeight = data.farmingActivit.length * 24 + 34;

                        Tablex.singleTable({
                            elmt: farmingActivit,
                            option: {
                                data: data.farmingActivit,
                                width: elmtWidth, height: elmtHeight,
                                columns: [
                                    { data: 'field', type: 'text', className: 'htCenter htMiddle', editor: false },
                                    { data: 'farmingActivit_1', type: 'text', className: 'htCenter htMiddle', editor: false },
                                    { data: 'farmingActivit_2', type: 'text', className: 'htCenter htMiddle', editor: false },
                                    { data: 'farmingActivit_3', type: 'text', className: 'htCenter htMiddle', editor: false },
                                    { data: 'farmingActivit_4', type: 'text', className: 'htCenter htMiddle', editor: false },
                                    { data: 'farmingActivit_5', type: 'text', className: 'htCenter htMiddle', editor: false },
                                    { data: 'farmingActivit_6', type: 'text', className: 'htCenter htMiddle', editor: false }
                                ],
                                stretchH: 'all', fillHandle: false,
                                rowHeaders: false, autoWrapRow: true,
                                colHeaders: [ '田类', '漫灌', '滴灌', '喷灌', '机耕', '施肥', '返肥' ]
                            }
                        });
                    }, 100);
                }
            });
        }
    }
});

function disSituationreload( param ) {
    var aimset = $("#choose_city").find("input:checkbox:checked"),
        starttime = $("#start_t").val(),
        endtime = $("#end_t").val(),
        //用于比较大小
        start_time = new Date(starttime).getTime(),
        end_time = new Date(endtime).getTime();
    console.log(starttime + "--" + endtime);    
    if( aimset.length <= 0){
        Popup.tipPopup({
            type: "toast",
            content: "请选择城市"
        });
    } else if(endtime == "" || starttime == ""){
        Popup.tipPopup({
            type: "toast",
            content: "请选择起止时间"
        });
    } else if(end_time < start_time){
        Popup.tipPopup({
            type: "toast",
            content: "截止时间小于开始时间"
        });
    } else{
        var areacode = [],
            areaCode = "";
        for(let t=0;t<aimset.length;t++){
            areacode[t] = aimset[t].value;
        }
        endtime = endtime + " 23:59:59";
        areaCode = areacode.join(',');
        console.log(areaCode);
        Loading.basic(); //加载图
        $.ajax({ 
            url: "http://118.25.235.213:8020/ChinaAPP/cloud/disaster/getPageDisasterList?pageNum=1&pageSise=12&type=1&areaCode=" + areaCode + "&beginTime=" + starttime + "&endTime=" + endtime,
            type: "GET",
            dataType: "json", 
            success: function(reuslt) {    
                Loading.remove();       
                let data = reuslt.data,//[ param.className ];
                    disUploadInfo = ``;
                    if(data == null || data.length <= 0){
                        disUploadInfo = `<li class="list_li" style="border: none; text-align: center; line-height: 60px;">暂无数据<li>`;
                        $(".disUploadInfo_ul").html(disUploadInfo);
                        $("#agri_more").attr("disabled","disabled");
                    }else{
                        $("#agri_more").removeAttr("disabled");
                        let datelength = data.length;
                        if(datelength >= 3){
                            datelength = 3
                        }
                        for ( let x = 0; x < datelength; x++ ) {
                            var url = "";
                            if( data[x].disaImgs == null ){
                                url = "../image/image/noagrimage.png";
                            }else {
                                var imgArray = data[x].disaImgs.split(","); 
                                    url = "http://118.25.235.213:8020/ChinaAPP/"+ imgArray[0];
                            }
                            var type = "";
                            if( data[x].leve1Name == null ){
                            }else {
                                type += data[x].leve1Name;
                            }
                            if( data[x].descriptTypeName == null ){
                            }else {
                                type += ","+data[x].descriptTypeName;
                            }
                            disUploadInfo += `<li class="list_li">
                                                <div class="img">
                                                    <img src="${ url }" onclick="showimgdiv('${ url }')"/>
                                                </div>
                                                <div class="info">
                                                    <h title="${ data[x].userShowName }">用户名: ${ data[x].userShowName }</h>
                                                    <div class="typediv">`
                                                    for(let v=0;v<type.split(",").length;v++){
                                                        if(v==0){
                                                            disUploadInfo += `<div class="borderdiv">${ type.split(",")[v] }</div>`;
                                                        }else{
                                                            disUploadInfo += `<div class="borderdiv" style="margin-left: 5px;">${ type.split(",")[1] }</div>`;
                                                        }
                                                    }                                                     
                                  disUploadInfo += `</div>
                                                    <div class="disUploadInfo_des" title="${ data[x].descript }">${ data[x].descript }</div>
                                                    <span style="width: 100%;">发布时间: ${ data[x].createtime.substring(0, 10) }</span>
                                                </div>
                                            </li>`;
                                            // <span style="width: 100%;">发布时间: ${ data[x].createtime.substring(0, 10) }</span>
                        }
                
                        $(".disUploadInfo_ul").html(disUploadInfo);
                
                        // 加载更多信息
                        let moreBtn = param.insetElmt.querySelectorAll("button[name='more']");      
                        for ( let x = 0; x < moreBtn.length; x++ ) {
                            moreBtn[x].removeEventListener("click", Popup.moreInfoPanel, false);
                            moreBtn[x].addEventListener("click", function(e) {
                                Popup.moreInfoPanel(areaCode, data, starttime, endtime);
                            }, false);
                        }
                    }            
            }
        }); 
    }              
}

//展示大图
function showimgdiv(url){
    if( url.indexOf("http") >= 0){
            var imgView = `<div title="点击关闭图片" onclick="hideimgdiv()" class="disaimgdiv">
                             <img src="${url}">
                           </div>`;
        document.querySelector(".main").insertAdjacentHTML("beforeEnd", imgView);
    }
}

//隐藏
function hideimgdiv(){
    $(".disaimgdiv").remove();
}
